package me.moscrop.RootCommand.commands;

import java.io.File;
import java.util.List;
import java.util.logging.Logger;

import me.moscrop.RootCommand.utilities.Utility;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.util.config.Configuration;


public class Homes {

	private File file;
	private static Configuration config;

	
	public Homes(String pluginDir)
	{
		file = new File(pluginDir + File.separator + "Homes.yml");
			
		config = new Configuration(file);
        config.load();
        checkConfig();

        new File(pluginDir).mkdir();

        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
	}
	
	public void loadConfig()
	{
        config.load();
        checkConfig();
	}
	
	private void checkConfig()
	{
		List<String> selectedKit = config.getKeys();
		String warp;
		Logger log = Logger.getLogger("Minecraft");
		
		if(selectedKit.size() == 0)
		{
			return;
		}
		
		for(int i = 0; i < selectedKit.size(); i ++)
		{
			warp = selectedKit.get(i);
		
			String[] toCheck = { "X", "Y", "Z", "Pitch", "Yaw"};
			
			for(String stat : toCheck )
			{
				if(Utility.isNum(config.getProperty(warp + "." + stat)))
				{
					log.warning("WARNING, Property " + stat +" of home " + warp + " is incorrect, deleting.");
					config.removeProperty(warp);
				}
			}
			
			config.save();
			
		}
	}

	public boolean onCommand(CommandSender sender, String[] args)
	{
		
		if(Utility.isConsole(sender) == true)
		{
			return false;
		}
		
		
		//give instructions
		if(args.length == 0 || (args.length == 1 && (args[0].contentEquals(""))))
		{
			sendToHome((Player) sender);
			return true;
		}
		
		if(args[0].contentEquals("set"))
		{
			setHome((Player) sender);
			return true;
		}
		
		Player goingTo = sender.getServer().getPlayer(args[0]);
		if(goingTo == null)
		{
			//if user doesnt exist display sorrt
			sender.sendMessage(ChatColor.RED + "Warning, that user doesnt have home.");
		}else{
			sender.sendMessage(ChatColor.GREEN + "Sending you to " + goingTo.getDisplayName() + " home.");
			sendToHome((Player) sender, goingTo);
		}
		
		return true;
	}

	public void sendToHome(Player player)
	{
		sendToHome(player,player);
	}
	
	public void sendToHome(Player player, Player tpTo)
	{
		
		Location newLoci = getPlayerSpawn(player);
		
		if(newLoci == null)
		{
			player.sendMessage(ChatColor.RED + "Sorry a home has not been set for " + player.getName());
			return ;
		}
			
		//Teleport the user the the location
		tpTo.teleport(Utility.getSafeLocationAt(newLoci));
	}

	public static void sendToHome(PlayerRespawnEvent event)
	{
		Location newLoci = getPlayerSpawn(event.getPlayer());
		
		if(newLoci == null)
		{
			return;
		}else{
			event.setRespawnLocation(newLoci);
		}
	}
	
	private static Location getPlayerSpawn(Player player)
	{
		
		Object object = config.getProperty(player.getName());
		String playerName = player.getName();
		
		if(object == null)
		{
			return null;
		}
		
		World world = Bukkit.getWorld((String) config.getProperty(playerName + ".World"));
		
		Location newLoci = new Location(world,0,0,0);
		newLoci.setX((Double) config.getProperty(playerName + ".X"));
		newLoci.setY((Double) config.getProperty(playerName + ".Y"));
		newLoci.setZ((Double) config.getProperty(playerName + ".Z"));
		newLoci.setYaw(((Double) config.getProperty(playerName + ".Yaw")).floatValue());
		newLoci.setPitch(((Double) config.getProperty(playerName + ".Pitch")).floatValue());
		
		return newLoci;
	}
	
	public static void setHome(Player player) {
		
		Location loci = player.getLocation();
		String playerName = player.getName();
		

		
		config.setProperty(playerName + ".X", loci.getX());
		config.setProperty(playerName + ".Y", loci.getY());
		config.setProperty(playerName + ".Z", loci.getZ());
		config.setProperty(playerName + ".Yaw", loci.getYaw());
		config.setProperty(playerName + ".Pitch", loci.getPitch());
		config.setProperty(playerName + "." + "World", loci.getWorld().getName());
		
		player.sendMessage(ChatColor.GREEN + "Home set to current location.");
		config.save();
	}
	
}
